package cn.jdy.payment.service;

import cn.jdy.framework.log.BaseLog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Heavens on 2014/5/4.
 */
public class OnlinePayHandler {

	/**
	 * 从request中获取请求参数
	 *
	 * @param request
	 * @param isStream
	 * @return
	 */
	public static Map<String, String> getDataFromRequest(javax.servlet.http.HttpServletRequest request, boolean isStream) {
		Map<String, String> map = new HashMap<String, String>();
		if(isStream) {
			try {
				BufferedReader in = null;
				try {
					in = new BufferedReader(new InputStreamReader(request.getInputStream()));
					String line = null;
					String result = "";
					while((line = in.readLine()) != null) {
						result += line;
					}
					map.put("xml", result);
				} catch(Exception e) {
					BaseLog.e(OnlinePayHandler.class, "getDataFromRequest", e);
				} finally {
					if(in != null) {
						try {
							in.close();
						} catch(IOException e) {
							BaseLog.e(OnlinePayHandler.class, "getDataFromRequest", e);
						}
					}
				}
			} catch(Exception e) {
				BaseLog.e(OnlinePayHandler.class, "getDataFromRequest", e);
			}
		} else {
			//将reqeust中的所有请求参数放入map中
			for(Iterator<Map.Entry<String, String[]>> iter = request.getParameterMap().entrySet().iterator(); iter.hasNext(); ) {
				Map.Entry<String, String[]> e = iter.next();
				String[] values = e.getValue();
				String valueStr = "";
				for(int i = 0; i < values.length; i++)
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				map.put(e.getKey(), valueStr);
			}
		}
		return map;
	}

}
